package com.framework.loippi.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.entity.Principal;
import com.framework.loippi.entity.Subscribe;
import com.framework.loippi.plugin.wxapppay.miniprogrampay.PayUtils;
import com.framework.loippi.service.SubscribeService;
import com.framework.loippi.support.APIPrincipal;
import com.framework.loippi.support.Page;
import com.framework.loippi.support.Pageable;
import com.framework.loippi.utils.ParameterUtils;
import com.framework.loippi.utils.RandomUtils;
import com.framework.loippi.utils.StringUtil;
import com.qcloud.cos.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SubscribeController
 * @Description TODO
 * @Author fsociety
 * @Date 29/11/2019 下午5:45
 * @Version 1.0
 */

@Controller("apiSubscribeController")
@RequestMapping("/api/subscribe")
@Api(tags = {"预约信息"})
public class SubscribeController {

    @Resource
    SubscribeService subscribeService;


    @RequestMapping(value = "/payDoctor.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("支付挂号费")
    public @ResponseBody
    String payDoctor(@RequestBody @Param(value = "obj") JSONObject requestJson, HttpServletRequest request) throws ParseException {
        APIPrincipal principal = getPrincipal(request);
        JSONObject json = JSON.parseObject(requestJson.getString("obj"));
        Subscribe subscribe = JSON.toJavaObject(JSONObject.parseObject(json.toString()), Subscribe.class);
        String subscribeId = subscribeService.buildSubscribeId(subscribe.getDoctorId(), subscribe.getDepartId(), subscribe.getPatientId(), subscribe.getSubscribeTime(), subscribe.getStatus(), subscribe.getType());
//      真实价格，上线之后复原
//        String total_fee = subscribeService.find(Long.valueOf(subscribeId)).getRegistration().toString();
        Subscribe subscribed = subscribeService.find(Long.valueOf(subscribeId));
//      测试价格
        String total_fee = "1";
//      随机字符串
        String randomString = "yz" + RandomUtils.getRandomNumberString(3) + subscribeId;
        String notify_url = "/api/payCallBack/subscribePay/" + 1 + "/" + subscribeId + ".json";
        Map<String, Object> map = PayUtils.wxPublicAppPay(principal.getOpenId(), subscribeId, randomString, Integer.valueOf(total_fee), notify_url, request);
        map.put("subscribe", subscribed);
        return ApiUtils.success(map);
    }

//    @RequestMapping(value = "/generate.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
//    @ApiOperation(value = "生成预约", notes = "{}")
//    public @ResponseBody
//    String generate(@RequestBody @Param(value = "obj") JSONObject requestJson) {
//        JSONObject json = JSON.parseObject(requestJson.getString("obj"));
//        Long nowNum = subscribeService.findSubNumByDate(json.getString("subscribeTime"));
//        synchronized (SubscribeController.class) {
//            if (nowNum == null || nowNum == 0) {
//                nowNum = 1L;
//            } else {
//                nowNum++;
//            }
//        }
//        json.put("subscribeNu", nowNum);
//        json.put("create_time", new Date());
//        Long save = subscribeService.save(JSON.toJavaObject(JSONObject.parseObject(json.toString()), Subscribe.class));
//        return ApiUtils.success(json);
//    }

    @RequestMapping(value = "/findFinished.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询往期预约", notes = "{}")
    public @ResponseBody
    String findFinished(Long patientId, Integer currentPage, Integer pageSize) {
        int curPage = (currentPage - 1) * pageSize;
        List list = subscribeService.findFinished(patientId, curPage, pageSize);
        Integer total = subscribeService.findAllFinished(patientId);
        Map<String, Object> map = new HashMap<>();
        map.put("obj", list);
        map.put("total", total);
        map.put("currentPage", currentPage);
        return ApiUtils.success(map);
    }

    @RequestMapping(value = "/findSicking.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询进行中预约", notes = "{}")
    public @ResponseBody
    String findHealing(Long patientId) {
        List<Subscribe> list = subscribeService.findSicking(patientId);

        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/findSick.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询待就诊预约", notes = "{}")
    public @ResponseBody
    String findHeal(Long patientId) {
        List<Subscribe> list = subscribeService.findSick(patientId);

        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/findDoing.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询进行中的就诊", notes = "{}")
    public @ResponseBody
    String findDoing(Long patientId) {
        List<Subscribe> list = subscribeService.findDoing(patientId);

        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/findDid.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询当天结束的就诊", notes = "{}")
    public @ResponseBody
    String findDid(Long patientId) {
        List<Subscribe> list = subscribeService.findDoing(patientId);

        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/findById.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "根据id查询预约", notes = "{}")
    public @ResponseBody
    String findById(String subscribeId) {
        Subscribe subscribe = subscribeService.find(Long.parseLong(subscribeId));
        return ApiUtils.success(subscribe);
    }

    @RequestMapping(value = "/cancel.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "取消预约", notes = "{}")
    public @ResponseBody
    String cancel(Subscribe subscribe) {
        subscribeService.update(subscribe);

        return ApiUtils.success();
    }

    @RequestMapping(value = "/findByDateAndDoctorId.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("根据日期查询预约时间")
    public @ResponseBody
    String findByDate(@Param(value = "doctorId") Long doctorId, @Param(value = "subscribeDate") String subscribeDate) {
        List<Subscribe> subscribes = subscribeService.findByDateAndDoctorId(subscribeDate, doctorId);
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        for (Subscribe s : subscribes) {
            list.add(sdf.format(s.getSubscribeTime()));
        }
        return ApiUtils.success(list);
    }

    @RequestMapping(value = "/findSubscribeText.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation("查询预约说明")
    public @ResponseBody
    String findSubscribeText() {
        String subscribeText = subscribeService.findSubscribeText();

        return ApiUtils.success(subscribeText);
    }

    public APIPrincipal getPrincipal(HttpServletRequest request) {
        HttpSession session = request.getSession();
        APIPrincipal principal = (APIPrincipal) session.getAttribute(APIPrincipal.PREFIX_USER_SESSION);
        return principal;
    }


    @RequestMapping(value = "/list.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "查询所有预约", notes = "{}")
    public @ResponseBody
    String list(Long uid, Integer currentPage, Integer pageSize) {
        int curPage = (currentPage - 1) * pageSize;
        List list = subscribeService.findAllByPatientId(uid, curPage, pageSize);
        Integer total = subscribeService.findAllByPatientId(uid);
        Map<String, Object> map = new HashMap<>();
        map.put("obj", list);
        map.put("total", total);
        map.put("currentPage", currentPage);
        return ApiUtils.success(map);
    }

}
